package com.zz.controller;

import com.zz.common.Result;
import com.zz.pojo.User;
import com.zz.service.UserService;
import com.zz.util.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
public class UserController {

    @GetMapping("user")
    public String toUserHtml(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();
        session.setAttribute("money", 100);

        Cookie cookie = new Cookie("name", "zhangsan");
        cookie.setMaxAge(30);
        response.addCookie(cookie);
        return "user.html";
    }

    @Autowired
    private UserService userService;
    List<User> userList= new ArrayList<>();
    @RequestMapping("add")
    @ResponseBody
    public Result add(@RequestBody User user,HttpServletRequest request){
        HttpSession session = request.getSession();
        Object money = session.getAttribute("money");
        System.out.println(money);

        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            System.out.println(cookie.getName()+cookie.getValue());
        }

        System.out.println(user);
        userList.add(user);
        int i = insertUser(user.getUsername(), user.getPassword());
        System.out.println("受影响的行数："+i);
        return Util.success(userList);
       // return Util.error(null);
    }

    @PostMapping("insertUser")
    @ResponseBody
    public int insertUser(String username, String password){
        return userService.insertUser(username,password);
    }

}
